package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.common.util.JsonUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.AttachmentModuleVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.AttachmentVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.AssemblyAttrDtoUtils;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;
import com.ztesoft.bss.base.entity.StaticAttrDO;
import com.ztesoft.bss.common.util.SpringUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 附件和备注模块
 */
@Service
public class AttachmentModuleHandler extends AbstractModuleHandler {

    @Autowired
    private IQuerySceneCommonService querySceneCommonService;
    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Override
    public List<AttachmentModuleVO> execute(AcceptContext context, SceneModule sceneModule) {

        SceneNewOfferSeneVO sceneAccountInfoVo = (SceneNewOfferSeneVO) context.getSceneVo();
        String moduleId = sceneModule.getKiteModule().getModuleId();
        AttachmentModuleVO attachmentModuleVO = getAttachmentModule(context, Boolean.TRUE, moduleId);
        setModuleAlert(attachmentModuleVO, context, moduleId);
        sceneAccountInfoVo.setAttachment(attachmentModuleVO);
        // 批量受理部分环节，不允许编辑
        if (BatchAcceptUtil.isBatchNode(context.getAcceptRequest().getSceneInstId())
            || BatchAcceptUtil.batchNodeResetIsEdit(context.getAcceptRequest().getSceneInstId())) {
            attachmentModuleVO.setIsEdit("F");
        }
        return Collections.singletonList(attachmentModuleVO);
    }

    @Override
    public List<ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        AttachmentModuleVO attachmentModuleVO = null;
        // 特殊处理-受理单补录
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        String moduleId = sceneModule.getKiteModule().getModuleId();
        String taskCode = querySceneInstService.getExtParameterValue(context.getAcceptRequest().getSceneInstId(), "taskCode");
        if ("OrderAddRecordWLWXS".equals(taskCode)) {
            attachmentModuleVO = getAttachmentModule(context, Boolean.TRUE, moduleId);
        }
        else{
            attachmentModuleVO = getAttachmentModule(context, Boolean.FALSE, moduleId);
        }
        SceneNewOfferSeneVO sceneNewOfferSeneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        setModuleAlert(attachmentModuleVO, context, moduleId);
        sceneNewOfferSeneVO.setAttachment(attachmentModuleVO);
        return Collections.singletonList(attachmentModuleVO);
    }

    private AttachmentModuleVO getAttachmentModule(AcceptContext context, Boolean isEditWithRemark, String moduleId) {
        AttachmentModuleVO attachmentModuleVO = new AttachmentModuleVO();

        List<AttachmentVO> attachmentList = new ArrayList<>();

        List<InstAttrDTO> attrConfigs = querySceneCommonService.listCommonAttrs(context.getAcceptRequest().getSceneInstId(), context.getAcceptRequest().getCustId()).getResultObject();
        List<InstAttrDTO> showAttrConfigs = new ArrayList<>();
        if (KiteListUtils.isNotEmpty(attrConfigs)) {
            for (InstAttrDTO instAttrDTO : attrConfigs) {
                if (!isEditWithRemark) {
                    instAttrDTO.setIsEdit("F");
                }
                //只拿附件和备注这两个属性
                if (LocalKeyConsts.COMMON_ATTR_KEY_REMARK.equals(instAttrDTO.getFieldName())) {
                    attachmentModuleVO.setRemark(Optional.ofNullable(instAttrDTO.getValue()).orElse(""));
                    showAttrConfigs.add(instAttrDTO);
                }
                else if (LocalKeyConsts.COMMON_ATTR_KEY_ATTACHMENT.equals(instAttrDTO.getFieldName()) && KiteStringUtils.isEqual(moduleId, instAttrDTO.getModuleId())) {
                    if (Objects.nonNull(instAttrDTO.getValue())) {
                        attachmentList.addAll(JsonUtils.parseArray(instAttrDTO.getValue(), AttachmentVO.class));
                    }
                    else {
                    	//返回空json到前端
                    	instAttrDTO.setValue("[]");
                    }
                    // 针对特殊业务需要提供模板单下载 节点内新增内容提供前台展示
                    addFileDownload(context,instAttrDTO);
                    showAttrConfigs.add(instAttrDTO);
                }
            }
        }
        List<CommonAttrVO> commonAttrList =  AssemblyAttrDtoUtils.assemblyVO(showAttrConfigs);
        attachmentModuleVO.setAttachmentAttr(commonAttrList);
        attachmentModuleVO.setAttachment(attachmentList);
        // 批量受理部分环节，不允许编辑
        if (BatchAcceptUtil.isBatchNode(context.getAcceptRequest().getSceneInstId())) {
            attachmentModuleVO.setIsEdit("F");
        }
        String sceneInstId = context.getSceneVo().getSceneInstId();
        KiteSceneInst sceneInst = this.querySceneInstService.getSceneInst(sceneInstId);
        String rootInstId = sceneInst.getRootInstId();
        KiteInst inst = querySceneInstService
                .getKiteInst(KiteWebContext.getContext().getCustId(), InstType.MAIN_OFFER_INST,
                    rootInstId);
        if (KiteObjectUtils.isEmpty(inst)) {
            inst = querySceneInstService.getKiteInst(KiteWebContext.getContext().getCustId(), InstType.GIFT_OFFER_INST,rootInstId);
        }
        if(!KiteObjectUtils.isEmpty(inst)){
            String offerId = inst.getSpecId();
            String cateId  = Optional.ofNullable(OfferCache.get(offerId)).map(Offer::getCateId).orElse("");
            if(KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())){
                attachmentModuleVO.setProdFlag("SX");
            }
        }
        return attachmentModuleVO;
    }

    public void addFileDownload(AcceptContext context, InstAttrDTO instAttrDTO) {
        List<StaticAttrDO> staticAttrDO = new ArrayList<>();
        String sceneTemplateId = context.getAcceptRequest().getSceneTemplateId();
        String serviceOfferId = context.getAcceptRequest().getServiceOfferId();
        String cateId = CuccPosServiceUtils.getCateId(context.getAcceptRequest().getSceneInstId(), context.getAcceptRequest().getCustId());
        // 根据TemplateId和serviceOfferId、cateId查询配置数据
        List<DcPublic> dcPublics = DcPublicCache.getByPcode(serviceOfferId, sceneTemplateId, cateId);
        if (KiteListUtils.isNotEmpty(dcPublics)) {
            dcPublics.stream().forEach(dcPublic -> {
                StaticAttrDO staticAttr = new StaticAttrDO();
                // 前台展示名称
                String showName = dcPublic.getCodea();
                // 下载后文件名称
                String downName = dcPublic.getCodeb();
                // 配置对应模板可以下载的文件路径
                String urlAddress = dcPublic.getCodec();
                staticAttr.setAttrValue(showName);
                staticAttr.setAttrValueDesc(downName);
                staticAttr.setParam1(urlAddress);
                staticAttrDO.add(staticAttr);
                staticAttr = new StaticAttrDO();
            });
            instAttrDTO.setAttrValues(staticAttrDO);
        }
    }

    /**
     * 设置模块提示信息
     */
    private void setModuleAlert(AttachmentModuleVO attachmentModuleVO,AcceptContext context, String moduleId){
        String serviceOfferId = context.getAcceptRequest().getServiceOfferId();
        if (KiteStringUtils.equals(serviceOfferId,"2826")){
            String cateId = CuccPosServiceUtils.getCateId(context.getAcceptRequest().getSceneInstId(), context.getAcceptRequest().getCustId());
            List<DcPublic> dcPublicList = DcPublicCache.getByPcode("202201191","MODULE_ALERT",cateId);
            if (Objects.nonNull(dcPublicList)){
                DcPublic dcPublic = dcPublicList.stream().filter(dcPub -> KiteStringUtils.equals(dcPub.getCodea(),moduleId)).findFirst().orElse(null);
                if (Objects.nonNull(dcPublic)){
                    //提示信息
                    String alert = dcPublic.getPname();
                    attachmentModuleVO.setAlert(alert);
                }
            }

        }
    }
}
